
#include "Attribute.h"
#include <iostream>

Attribute :: Attribute () {
	data = 0;
	len = 0;
}

Attribute :: ~Attribute () {
	delete data;
	data = 0;
	len = 0;
}

void Attribute :: LoadInt (int loadMe) {

	if(data != NULL)
		delete data;
	len = sizeof (int);
	data = new char[len];
    memmove (data, &loadMe, len);
}

void Attribute :: LoadDouble (double loadMe) {

	if(data != NULL)
		delete data;
	len = sizeof (double);
	data = new char[len];
	memmove (data, &loadMe, len);
}

void Attribute :: LoadString (char *loadMe) {

	if(data != 0 || data != NULL)
		delete data;
	len = strlen (loadMe) + 1;
	data = new char[len];
	strcpy (data, loadMe);
}

int Attribute :: GetInt () {
	return *((int *) data);
}

double Attribute :: GetDouble () {
	return *((double *) data);
}

char *Attribute :: GetString () {
	return strdup (data);
}

int Attribute :: ToBinary (char *here) {

	// first, write out the size
	memmove (here, &len, sizeof(int));

	// then write out the data
	memmove (here + sizeof (int), data, len);

	// and return the number of bytes copied
	return len + sizeof (int);
}

int Attribute :: FromBinary (char *here) {

	// delete anything we now have
	delete data;
	
	// read in the size
	memmove (&len, here, sizeof(int));

	// allocate the new memory and read the bytes
	data = new char[len];
	memmove (data, here + sizeof (int), len);

	// return the number of bytes copied
	return len + sizeof (int);
}

// easy!  Just return the total size we'd be after a call to ToBinary
int Attribute :: GetLength () {
	return len + sizeof (int);
}


